package com.byx.chatclient.im;

import android.util.Log;

import com.byx.chatclient.entity.message.Message;
import com.byx.chatclient.utils.ThreadPoolUtil;
import com.byx.imclientutil.entity.BaseMessage;

/**
 * MessageProcessor
 *
 * @author Superb
 * @date 2021/4/5 10:22
 */
public class MessageProcessor implements IMessageProcessor {
    public static final String TAG = MessageProcessor.class.getSimpleName();

    private static class Singleton {
        private static final IMessageProcessor INSTANCE = new MessageProcessor();
    }

    public static IMessageProcessor getInstance() {
        return Singleton.INSTANCE;
    }

    @Override
    public void receiveMsg(BaseMessage baseMessage) {
        ThreadPoolUtil.runInBackground(() -> {
            try {
                IMessageHandler messageHandler = MessageHandlerFactory.getHandlerByMsgType(baseMessage.getType());
                if (messageHandler != null) {
                    messageHandler.execute(baseMessage);
                } else {
                    Log.e(TAG, "未找到消息处理handler，msgType=" + baseMessage.getType());
                }
            } catch (Exception e) {
                Log.e(TAG, "消息处理出错，reason=" + e.getMessage());
            }
        });
    }

    @Override
    public void sendMsg(BaseMessage baseMessage) {
        ThreadPoolUtil.runInBackground(() -> {
            boolean isActive = ImClientBoot.getInstance().isActive();
            if (isActive) {
                ImClientBoot.getInstance().sendMessage(MessageConverter.toMsg(baseMessage));
            } else {
                Log.e(TAG, "发送消息失败");
            }
        });
    }

    @Override
    public void sendMsg(Message message,boolean isSingleChat) {
        this.sendMsg(MessageConverter.toImMessage(message, isSingleChat));
    }
}
